﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
using Wombat.Common;

namespace Client.RawDataSimulator
{
    public partial class SimulationManager : Form
    {
        private List<MainForm> _forms;

        public SimulationManager()
        {
            InitializeComponent();
        }

        private XName Gname(string name)
        {
            return XName.Get(name);
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(ProgramText.Text))
            {
                new MainForm();
                return;
            }
            var doc = XDocument.Parse(ProgramText.Text);
            var data = doc.Element(Gname("Tags")).NullSafe(l => l.Elements(Gname("Tag")))
                          .Select(l => new
                              {
                                  Formula = (string) l.Attribute(Gname("Formula")),
                                  TagId = (int) l.Attribute(Gname("Id")),
                                  Interv = (int) l.Attribute(Gname("TimerInterval")),
                                  Randomness = (int) l.Attribute(Gname("Randomness")),
                                  ParamVals = l.Value.Replace(";", "\r\n"),
                                  Form = new MainForm()
                              })
                          .ToList();
            foreach (var dat in data)
            {
                dat.Form.SetData(dat.Formula, dat.TagId, dat.Randomness, dat.Interv, dat.ParamVals);
                dat.Form.Show();
            }
            _forms = data.Select(d => d.Form).ToList();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_forms != null && _forms.Any())
            {
                _forms.ForEach(f => f.StartSimulation());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (_forms != null && _forms.Any())
            {
                _forms.ForEach(f => f.StopSimulation());
            }
        }
    }
}
